package thread;

/**
 * 并发安全的API
 * StringBuilder不是线程安全的,StringBuffer是线程安全的;
 * 多线程的场景下为了保证数据安全,应该使用StringBuffer;
 */
public class Demo09AsyncApi {
    public static void main(String[] args) {
        //StringBuilder sb = new StringBuilder();
        StringBuffer sb = new StringBuffer();
        //线程1:
        Thread t1 = new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    sb.append("a");
                }
            }
        };
        //线程2:
        Thread t2 = new Thread(){
            public void run(){
                for (int i = 0; i < 1000; i++) {
                    sb.append("b");
                }
            }
        };

        t1.start();
        t2.start();

        //主线程阻塞,等待t1和t2两个线程执行完成;
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(sb.length());
    }
}











